// @flow
import React from 'react'
import { message, Form, Input, Select, Button, Upload, Icon } from 'antd'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import { getSpecs, getDeviceType } from 'utils/GeneralOptions'
import styles from './Home.css'

type Props = {
  form: Object,
  history: Object
}

const FormItem = Form.Item
const Option = Select.Option

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0
    },
    sm: {
      span: 14,
      offset: 6
    }
  }
}

type States = {
  data: Array<any>,
  specs: Array<any>,
  types: Array<any>,
  pointData: Array<any>,
  visible: boolean,
  imageUrl: string,
  remoteImageUrl: string
}
class DeviceTypeAdd extends React.Component {
  props: Props
  state: States
  goBack: Function
  changeFile: Function
  beforeUpload: Function
  getPointData: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      data: [],
      specs: [],
      types: [],
      pointData: [],
      visible: false,
      imageUrl: '',
      remoteImageUrl: ''
    }
    this.goBack = this.goBack.bind(this)
    this.changeFile = this.changeFile.bind(this)
    this.beforeUpload = this.beforeUpload.bind(this)
    this.getPointData = this.getPointData.bind(this)
  }
  componentWillMount () {
    this.getPointData()
  }

  getPointData () {
    universalFetch(`${__SERVICE_API__}device/templates/monitors/points`)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      this.setState({
        pointData: json.result
      })
      // pointData = json.result
    })
    .catch((error) => {
      handleFetchError(error)
      console.error(error)
    })
  }

  changeFile (info) {
    const response = info.file.response
    if (response && response.code === 200000) {
      this.setState({
        imageUrl: response.result.name,
        remoteImageUrl: response.result.url
      })
    }
  }

  beforeUpload (file) {
    const type = file.type.toLocaleLowerCase()
    if (type.indexOf('image/') === -1) {
      message.error('只能上传图片', 3)
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('图片必须小于2MB!')
    }
    return type.indexOf('image/') > -1
  }
  /**
   * 提交表单
   * @param  {[type]} e [description]
   * @return {[type]}   [description]
   */
  handleSubmit = (e) => {
    e.preventDefault()
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      const { imageUrl } = this.state
      const values = {
        ...Object.assign({}, fieldsValue, { imageUrl }),
        isRoot: 1
      }
      universalFetch(`${__SERVICE_API__}device/templates/devices`, {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        method: 'POST',
        body: JSON.stringify(values)
      })
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        message.success('设备模板添加成功')
        this.props.history.push('/business/device-type')
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
        message.info('设备模板添加失败')
      })
    })
  }

  /**
   * [handleTypeChange description]
   * @param  {[type]} value [description]
   * @return {[type]}       [description]
   */
  handleTypeChange = (value) => {
    getSpecs(value, (json) => {
      this.setState({
        specs: json.result.map((d, i) => {
          return <Option key={d.id} value={d.value}>{d.label}</Option>
        })
      })
    })
  }

  componentDidMount () {
    getDeviceType((json) => {
      this.setState({
        types: json.result.map((d, i) => {
          return <Option key={d.id} value={d.value}>{d.label}</Option>
        })
      })
    })
  }
  goBack () {
    this.props.history.push('/business/device-type')
  }
  render () {
    const { getFieldDecorator } = this.props.form
    const { remoteImageUrl, pointData } = this.state
    const token = localStorage.getItem('asset_token')
    return (
      <div className={styles['main']}>
        <Form onSubmit={this.handleSubmit}>
          <FormItem {...formItemLayout} label='名称' hasFeedback>
            {getFieldDecorator('name', {
              rules: [
                { required: true, message: '请填写名称', whitespace: true }
              ]
            })(
              <Input placeholder='请填写名称' ref={(e) => {
                document.querySelector('#name').focus()
              }} />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='类型' hasFeedback>
            {getFieldDecorator('type', {
              rules: [
                { required: true, message: '请选择类型' }
              ]
            })(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }}
                placeholder='请选择类型'
                onChange={this.handleTypeChange}>
                {this.state.types}
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='型号' hasFeedback>
            {getFieldDecorator('spec', {})(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }}
                placeholder='请选择型号'
                >
                {this.state.specs}
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='测点' hasFeedback>
            {getFieldDecorator('pointId', {})(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }}
                placeholder='请选择测点'
                >
                <Option key='-1' value='' />
                {
                  pointData.map((d, i) => {
                    return <Option key={i} value={d.id}>{d.sensorName}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='设备模板图片'>
            {
              getFieldDecorator('imageUrl', {})(
                <Upload
                  {...{
                    name: 'file',
                    className: styles['avatar-uploader'],
                    action: `${__SERVICE_API__}static/statics`,
                    headers:{ 'X-Auth':token },
                    onChange: this.changeFile,
                    beforeUpload: this.beforeUpload,
                    showUploadList: false
                  }}
                  >
                  {
                    remoteImageUrl
                    ? <div className={styles['image-preview']}>
                      <img src={remoteImageUrl} style={{ width: '100%' }} />
                      <div className={styles['over-avatar']}>
                        更换图片
                      </div>
                    </div>
                    : <Button style={{ width: '150px' }}>
                      <Icon type='upload' />上传图片
                    </Button>
                  }
                </Upload>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='备注'>
            {getFieldDecorator('remark', {})(
              <Input placeholder='请填写备注' type='textarea'
                autosize={{ minRows: 2 }} />
            )}
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Button type='primary' htmlType='submit' size='large'>保存</Button>
            <Button size='large' style={{ marginLeft: '20px' }} onClick={this.goBack}>返回</Button>
          </FormItem>
        </Form>
      </div>
    )
  }
}

export default Form.create()(DeviceTypeAdd)
